#include "recent_contact_request.h"

#include <iostream>
#include <sstream>
#include <string>
#include <map>
#include <algorithm>
#include <boost/foreach.hpp>

#include "base/logging.h"
#include "base/json_escape.h"
#include "im/common/common.h"
#include "functor.h"

namespace imserver {
namespace fcgi {

extern void GetResponseBody(std::string& rsp_body, const RecentContactList& list, const std::string& callback);


bool RecentContactRequest::Response() {
  if (!fcgi_out_) {
    LOG_WARN("null fcgi_out!");
    return false;
  }

  ParseUserIdentity();
  std::string callback = ParseCallback();

  std::string rsp_header("Content-type: text/javascript; charset=utf-8\r\n\r\n");
  FCGX_PutS(rsp_header.c_str(), fcgi_out_);

  if (!callback.empty()) {
    RecentContactList recent_list;
    // login user
    if (qid_ > 0)
      RecentContactAdapter::Instance().GetContacts(qid_, 0, 50, &recent_list, 2);
    // unlogined
    if (temp_id_ > 0) {
      LOG_DEBUG("read unlogined user contacts.");
      RecentContactList temp;
      RecentContactAdapter::Instance().GetContacts(temp_id_, 0, 50, &temp, 2);
      std::remove_copy_if(temp.begin(), temp.end(), std::back_inserter(recent_list), IsExistInTheVector(recent_list));
    }

    if (recent_list.empty()) {
      static int64_t customer_guide_ids[] = {317126174, 317124696, 317121850, 317125217};
      recent_list.push_back(RecentContact());
      recent_list.back().uid = customer_guide_ids[rand() % (sizeof(customer_guide_ids) / sizeof(int64_t))];
    }

    std::string rsp_body;
    GetResponseBody(rsp_body, recent_list, callback);
    FCGX_PutS(rsp_body.c_str(), fcgi_out_);
  } else {
    std::string rsp_body("{errno:-1}");
    FCGX_PutS(rsp_body.c_str(), fcgi_out_);
  }

  return true;
}

}
}


